package com.gexiaobao.pigeon.ui.view;

import android.content.Context;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

/**
 * @Author : hxw
 * @Date : 2024/7/22 13:54
 * @Describe :
 */
public class CustomLayoutManager extends RecyclerView.LayoutManager {

    private int mTotalWidth;
    private int mTotalHeight;

    public CustomLayoutManager(Context context, int columns) {
        // 根据列数计算每个 Item 的宽度
        mTotalWidth = context.getResources().getDisplayMetrics().widthPixels;
        int itemWidth = mTotalWidth / columns;

        // 假设 Item 高度与宽度相等
        mTotalHeight = itemWidth * columns;
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT,
                RecyclerView.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        detachAndScrapAttachedViews(recycler);

        int offsetX = 0;
        int offsetY = 0;

        // 布局每个 Item
        for (int i = 0; i < getItemCount(); i++) {
            View view = recycler.getViewForPosition(i);
            addView(view);

            // 计算 Item 的位置
            measureChildWithMargins(view, 0, 0);
            int width = getDecoratedMeasuredWidth(view);
            int height = getDecoratedMeasuredHeight(view);
            layoutDecorated(view, offsetX, offsetY, offsetX + width, offsetY + height);

            offsetX += width;

            // 换行处理
            if (offsetX >= mTotalWidth) {
                offsetX = 0;
                offsetY += height;
            }
        }
    }

    @Override
    public boolean canScrollHorizontally() {
        return true;
    }

    @Override
    public boolean canScrollVertically() {
        return true;
    }

    @Override
    public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
        // 实现水平滑动逻辑
        offsetChildrenHorizontal(-dx);
        return dx;
    }

    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        // 实现垂直滑动逻辑
        offsetChildrenVertical(-dy);
        return dy;
    }
}

